import * as cmdbData from './cmdb.json';
//定义类型
type cmdbCell = { [colNum: number]: { v: string; s?: string } };
type cmdbRow = { [rowsNum: number]: any };
export function toExcel(cmdb = cmdbData): { dataModi: cmdbRow; dataDel: cmdbRow } {
  // 表头列文字 和 主键列
  const columnKey = 'id';
  const columns = ['id', 'name', 'amount'];
  const columnsText = ['ID', '名称', '数量'];

  let dataModi: cmdbRow = {};
  const cols = columns.length;
  //每个sheet上的标题行
  let header: cmdbCell = {};
  for (let i = 0; i < cols; i++) {
    header[i] = {
      v: columnsText[i],
      s: 'boldText',
    };
  }
  dataModi[0] = header;

  let colData: cmdbCell = {};
  //新增的数据
  for (let i = 0; i < cmdb.added.length; i++) {
    colData = {};

    columns.forEach((col, j) => {
      let r: any = cmdb.added[i];
      if (columnKey === col) {
        colData[j] = {
          v: r[col],
          s: 'keyText',
        };
      } else {
        colData[j] = {
          v: r[col],
        };
      }
    });

    dataModi[i + 1] = colData;
  }
  //修改的数据
  let num = Object.keys(dataModi).length;
  for (let i = 0; i < cmdb.changed.length; i++) {
    colData = {};

    let r: any = cmdb.changed[i];
    colData[0] = {
      v: r['key'][0],
      s: 'keyText',
    };
    for (const f in r['fields']) {
      colData[columns.indexOf(f)] = {
        v: `${r['fields'][f]['to']} (${r['fields'][f]['from']})`,
        s: 'modified',
      };
    }

    dataModi[num] = colData;
    num++;
  }

  //console.log('MODI ', dataModi);

  //删除的数据
  let dataDel: cmdbRow = {};
  dataDel[0] = header;
  for (let i = 0; i < cmdb.removed.length; i++) {
    colData = {};
    columns.forEach((col, j) => {
      let r: any = cmdb.removed[i];
      if (columnKey === col) {
        colData[j] = {
          v: r[col],
          s: 'keyText',
        };
      } else {
        colData[j] = {
          v: r[col],
          s: 'deleted',
        };
      }
    });

    dataDel[i + 1] = colData;
  }

  //console.log('DEL ', dataDel);
  return { dataModi, dataDel };
}
